package it.tukano.image;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

/** Extension of the imageio utilities */
public class ImageIOExt {

    /**
     * Instance initializer
     */
    ImageIOExt() {
    }

    /**
     * Read an image from a byte array
     * @param data the image bytes
     * @return the buffered image
     * @throws IOException if the bytes don't define a valid image
     */
    public static BufferedImage read(byte[] data) throws IOException {
        ByteArrayInputStream bin = new ByteArrayInputStream(data);
        return ImageIO.read(bin);
    }

    /**
     * Creates a scaled version of an image
     * @param width the width of the scaled image
     * @param height the height of the scaled image
     * @param image the image to scale
     * @return a new scaled image
     */
    public static BufferedImage createIcon(int width, int height, Image image) {
        BufferedImage scaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = scaled.createGraphics();
        graphics.drawImage(image, 0, 0, width, height, null);
        graphics.dispose();
        return scaled;
    }

    /**
     * Converts an image into a png array of bytes
     * @param image the image to convert
     * @return a new array of bytes
     * @throws IOException if the conversion fails due to a io exception
     */
    public static byte[] toPngBytes(Image image) throws IOException {
        if(image instanceof RenderedImage) {
            return toPngBytes((RenderedImage) image);
        } else {
            return toPngBytes((RenderedImage) toBufferedImage(image));
        }
    }

    /**
     * Convert an image into a buffered image
     * @param image the image to convert
     * @return a new buffered image
     */
    public static BufferedImage toBufferedImage(Image image) {
        BufferedImage buffer = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = buffer.createGraphics();
        graphics.drawImage(image, 0, 0, null);
        graphics.dispose();
        return buffer;
    }

    /**
     * Convert an image into a png byte array
     * @param image the image to convert
     * @return a new byte array
     * @throws IOException if the conversion fails due to an exception throw by ImageIO
     */
    public static byte[] toPngBytes(RenderedImage image) throws IOException{
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "png", out);
        return out.toByteArray();
    }
}
